'''
* This is the projet for Brtc LlmOps Platform
* @Author Leon-liao <liaosiliang@alltman.com>
* @Description //TODO 
* @File: provider_entity.py
* @Time: 2025/11/10
* @All Rights Reserve By Brtc
'''
import os
from typing import Any

import yaml
from pydantic import BaseModel, Field

from internal.lib.helper import dynamic_import
from .tool_entity import ToolEntity
class ProviderEntity(BaseModel):
    """服务商实体类，映射的时 数据provider.yaml里面的一条记录"""
    name:str #名字
    label:str # 标签
    description:str# 描述
    icon:str #图标
    background:str # 背景
    category:str # 分类信息
    created_at:int = 0 # 创建时间


class Provider(BaseModel):
    """服务提供商类 在该类下 可以获取所有该服务提供商的所有工具、描述、图标等多个信息"""
    name:str #服务商的名
    position:int #服务商前端显示的顺序
    provider_entity:ProviderEntity#服务商的实体类
    tool_entity_map:dict[str, ToolEntity] = Field(default_factory=dict)
    tool_func_map:dict[str, Any]= Field(default_factory=dict)

    def _provider_init(self):
        """服务提供商初始化函数"""
        #1、获取当前类路径,并计算对应服务提供商的地址/路径
        current_path = os.path.abspath(__file__)
        entities_path = os.path.dirname(current_path)
        provider_path = os.path.join(os.path.dirname(entities_path), "provider", self.name)

        #2、组装获取position.yaml的数据
        position_yaml_path = os.path.join(provider_path, "position.yaml")
        with open(position_yaml_path, "r", encoding="utf-8") as f:
            provider_yaml_data = yaml.safe_load(f)

        #3、循环读取位置信息并获取服务提供商名字
        for tool_name in provider_yaml_data:
            #4、获取工具的yaml数据
            tool_yaml_path = os.path.join(provider_path, f"{tool_name}.yaml")
            with open(tool_yaml_path, "r", encoding="utf-8") as f:
                tool_yaml_data = yaml.safe_load(f)

            #5、将工具的信息填充到tool_entity_map中
            self.tool_entity_map[tool_name] = ToolEntity(**tool_yaml_data)

            #6、动态导入对应的工具并填充到 tool_func_map中
            self.tool_func_map[tool_name] = dynamic_import(
                module_name=f"internal.core.tools.builtin_tools.provider.{self.name}",
                symbol_name = tool_name
            )



    def __init__(self, **kwargs):
        """构造函数,完成对服务提供商的初始化"""
        super().__init__(**kwargs)
        self._provider_init()


    def get_tool(self, tool_name:str)->Any:
        """根据工具的名字，获取工具函数"""
        return self.tool_func_map[tool_name]


    def get_tool_entity(self, tool_name:str)->ToolEntity:
        """根据工具名字获取工具的实体"""
        return self.tool_entity_map.get(tool_name)


    def get_tool_entities(self)->list[ToolEntity]:
        """获取所有服务商下所有工具实体"""
        return list(self.tool_entity_map.values())

